#include "RpcReadConfFile.hpp"
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <fstream>

//这里不用担心线程安全的问题，因为只有调用init才会进行这里的函数调用，而init是static静态函数全局只会调用一次

void RpcReadConfFile::PrintAllConf()
{
     if(_confMessageMap.empty())
     {
        std::cout << "not found include confmessage" << std::endl;
        return;
     }

     for(auto& e : _confMessageMap)
     {
        std::cout << e.first  << ":" << e.second << std::endl; 
     }
}


void RpcReadConfFile::Trim(std::string &str)
{
     //去除该字符串的前后空格
     size_t index1 = str.find_first_not_of(' ');
     str = str.substr(index1,std::string::npos);

     size_t index2 = str.find_last_not_of(' ');
     str = str.substr(0,index2+1);
}

std::string RpcReadConfFile::GetConfMapMessage(std::string key)
{
   auto it = _confMessageMap.find(key);
   if(it != _confMessageMap.end())
   return it->second;
   else
   return "";
}


void RpcReadConfFile::ReadConfFile(int argc, char **argv)
{
   // 打开RpcFileConf.txt文件，开始文件操作
   std::string file = "../configurationfile/";
   std::string conffile = argv[2];
   file = file + conffile;

   std::ifstream fp(file, std::ios::in | std::ios::binary );
   if (!fp.is_open())
   {
      std::cout << "open conffile"<< " " << file << " " << "failure" << std::endl;
      exit(EXIT_FAILURE);
   }

   std::string buffer;
   while(std::getline(fp,buffer))
   {
      //读取到了一行数据buffer，我们把这行数据分为key和value进行解析

      size_t index = buffer.find('=');
      if(index == std::string::npos)
      continue;

      std::string key = buffer.substr(0,index);
      std::string value = buffer.substr(index+1,std::string::npos);
      Trim(key);
      Trim(value);

      if(key[0] == 's' || key[0] == 'z')
      {
         _confMessageMap.insert(std::make_pair(key,value));
      }
   }


   fp.close();
}



